// index.js
const app = getApp()

import {
    checkLogin
} from "../../utils/utils"
import {
    getCartData,
    checkGoodsData,
    deletetGoodsData,
    goodsSteptepData
} from "../../request/request"
Page({
    data: {
        checked: true, //全选状态
        cartList: [], //所有商品列表
        cartTotal: {}, //商品总数信息
        isEdit: "编辑" //是否编辑状态
    },
    //步进器事件
    onChangeStep(e) {
       
        let item = e.currentTarget.dataset.item
        goodsSteptepData({
            goodsId: item.goods_id,
            id: item.id,
            number: e.detail,
            productId: item.product_id
        }).then(res => {
            this.validationCheckAll(res)
        })

    },
    //编辑按钮事件
    btnEdit(e) {
     
        if (this.data.isEdit == '编辑') {
            this.setData({
                isEdit: '完成编辑'
            })
        } else {
            this.setData({
                isEdit: '编辑'
            })
        }

    },
    //删除商品
    deleteGoodsFn(e) {
        deletetGoodsData(e.currentTarget.dataset.id + '').then(res => {
            this.validationCheckAll(res) //验证全选按钮状态
            app.Notify({
                type: "success",
                message: '删除成功'
            })

        })
    },
    //单个商品点击选中状态的色时候
    async singleChange(e) {
        // console.log(e.currentTarget.dataset.id);
        let productIds = e.currentTarget.dataset.id
        let isChecked = e.detail ? 1 : 0
        await checkGoodsData({
            isChecked: isChecked,
            productIds: productIds
        }).then(res => this.validationCheckAll(res) //验证全选状态
        )

    },
    //更新商品列表和验证全选状态函数
    validationCheckAll(res) {
        if (res.errno != 0) return

        let {
            cartList,
            cartTotal
        } = res.data
        this.setData({
            cartTotal,
            cartList
        })

        let tempCheckAll = this.data.cartList.some(item => {
            return item.checked == 0
        })
        console.log('验证', !tempCheckAll);
        this.setData({
            checked: !tempCheckAll
        })
    },
    //全选功能
    onChangeAllcheck(e) {
        let tempIdArr = this.data.cartList.map(item => {
            return item.product_id
        })
        let productIds = tempIdArr.join(',')
        let isChecked = e.detail ? 1 : 0
        this.setData({
            checked: e.detail,
        });
        checkGoodsData({
            isChecked: isChecked,
            productIds: productIds
        }).then(res => this.validationCheckAll(res)) //验证全选按钮状态
    },

    onLoad: function () {},
    onShow: async function () {
        //验证登录状态
        if (!checkLogin(true)) return
        //获取当前页面的tabbar对象,设置他的active值为当前页面索引，解决tabbar闪烁乱跳问题
        let tabbarObj = this.getTabBar()
        tabbarObj.setData({
            active: 2
        })
        //获取购物车信息
        await getCartData().then(res => this.validationCheckAll(res)) //验证全选按钮状态)

    }
})